package com.example.b_308.myapplication.controller;

import com.example.b_308.myapplication.R;
import com.example.b_308.myapplication.comment.utils.Global;
import com.example.b_308.myapplication.comment.utils.PhoneValidator;
import com.example.b_308.myapplication.comment.utils.StringValidator;
import com.example.b_308.myapplication.controller.base.BaseController;
import com.example.b_308.myapplication.model.Company;
import com.example.b_308.myapplication.model.Department;
import com.example.b_308.myapplication.model.Staff;
import com.example.b_308.myapplication.service.UserService;
import com.example.b_308.myapplication.view.user.login.IUserView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by B-308 on 2017/11/28.
 */
public class UserController extends BaseController {
    IUserView iUserView;
    UserService userService;
    public static List<Department> departmentList = new ArrayList<>();

    public UserController(IUserView iUserView) {
        this.iUserView = iUserView;
        userService = new UserService(iUserView);

    }

    public void loginDefault() {
        userService.loginDefault();
    }

    public void login(String phone, String password) {
        if (PhoneValidator.isPhoneNumber(phone)) {
            iUserView.fail(Global.getString(R.string.phone_error));
            return;
        } else if (password.length() < 6 || password.length() > 13) {
            iUserView.fail(Global.getString(R.string.password_error));
            return;
        }
        Staff staff = new Staff();
        staff.setPhone(phone);
        staff.put("password", password);
        userService.login(staff);
    }

    public void register(Company company, Staff staff) {
        Map<String, Object> map = company.getAttrs();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            staff.put("company_" + entry.getKey(), entry.getValue());
        }
        staff.put("company_departments",departmentList);
        userService.register(staff);
    }

    public void getCode(String phone, int type) {
        if (PhoneValidator.isPhoneNumber(phone)) {
            iUserView.fail(Global.getString(R.string.phone_error));
            return;
        }
        Staff staff = new Staff();
        staff.setPhone(phone);
        staff.put("type", type);
        userService.getCode(staff);
    }

    public static boolean checkPassword(String password, String surePassword) {
        if (StringValidator.isNotEmply(password) && StringValidator.isNotEmply(surePassword) && password.equals(surePassword)) {
            return true;
        }
        return false;
    }
}
